package cn.tedu.csmall.product.config;

import cn.tedu.csmall.product.filter.JwtAuthorizationFilter;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //处理“需要通过认证，但是实际上未通过认证就发起的请求”导致的错误
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                String message = "未检测到登录，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了JWT数据！）";
                JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED,message);
                response.setContentType("application/json; charset=utf-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.println(JSON.toJSONString(jsonResult));
                printWriter.close();
            }
        });


        //白名单
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/admin/login"
        };

        //解决复杂请求跨域问题
        http.cors();

        //禁用‘防止伪造的跨域攻击’这种防御机制
        http.csrf().disable();

        //配置URL的访问控制
        //注意，基于第一匹配原则，覆盖范围越大的匹配方法，应该配置在更后的位置
        http.authorizeRequests() //配置URL的访问控制
                //对OPTIONS请求放行
                /*.mvcMatchers(HttpMethod.OPTIONS,"/**")
                .permitAll()*/
                .mvcMatchers(urls) //匹配某些RUL
                .permitAll() //直接允许，即：不需要通过认证就可以直接访问
                .anyRequest()  //任何请求()
                .authenticated();  //以上配置的请求需要是通过认证的

        http.addFilterBefore(jwtAuthorizationFilter,
                UsernamePasswordAuthenticationFilter.class);

        //调用formLogin（）表示启用登录表单和登出页，如果未调用此方法，
        //则没有登录和登出页面
//        http.formLogin();
    }
}
